<template>
    <div>
       <div class="content">
            <div class="left">
                 <div class="left-inner">
                <el-form ref="form" :model="form" >
  <el-form-item label="缴费人员"  prop="name">
    <el-input v-model="form.name" placeholder="输入缴费人员"></el-input>
  </el-form-item>
    <el-form-item label="缴费名称" prop="product">
    <el-input v-model="form.product"  placeholder="输入缴费项目/名称"></el-input>
  </el-form-item>
  <el-form-item label="支付类型"  prop="type">
    <el-select v-model="form.type" placeholder="请选择支付方式"  clearable>
      <el-option label="支付宝支付" :value="1"></el-option>
      <el-option label="微信支付" :value="2"></el-option>
      <el-option label="银联支付" :value="3"></el-option>
    </el-select>
  </el-form-item>

  <el-form-item label="支付状态"  prop="status">
    <el-select v-model="form.status" placeholder="请选择支付状态"  clearable>
      <el-option label="已支付" :value="1"></el-option>
      <el-option label="未支付" :value="2"></el-option>

    </el-select>
  </el-form-item>

  <el-form-item label="活动时间"  prop="date1">
    <el-col :span="22">
         <el-date-picker
     
      type="daterange"
      range-separator="至"
      start-placeholder="开始日期"
      v-model="form.date1" style="width: 100%;"
      end-placeholder="结束日期">
    </el-date-picker>
     
    </el-col>
   
  </el-form-item>
   <el-form-item label="缴费金额"  prop="sum">
    <el-input v-model="form.sum" placeholder="输入缴费金额"></el-input>
  </el-form-item>
    <el-form-item label="缴费优先级" v-if="abc"  prop="priority">
    <el-input v-model="form.priority" placeholder="输入缴费优先级" ></el-input>
  </el-form-item>
     <el-form-item style="text-align: center; ">
  <el-button v-if="qbz" style="border: 0;color: #9CD8F7;" @click="lNone"><i class="el-icon-arrow-down"></i>更多</el-button>
  <el-button v-else style="border: 0;color: #9CD8F7;" @click="lBlock"><i class="el-icon-arrow-up"></i>收起</el-button>
  </el-form-item>
  

  <el-form-item>
 
    <el-button style="width: 140px;" type="info" @click="resetForm('form')">重置</el-button>
    <el-button style="width: 140px;" type="primary" @click="submitForm('ruleForm')">立即查询</el-button>
  </el-form-item>
</el-form>
</div>
            </div>
            <div class="right">
                <div class="right-top">
                    <h1>续费列表</h1>
                    <el-button type="primary" icon="el-icon-download" @click="exportAll">导出</el-button>
                </div>

                 <el-table
    :data="tableData"
   v-loading="Loading"
    border
      stripe
    style="width: 100%">
    <el-table-column
      prop="payname"
       height="50"
      label="续费产品"
       align="center"
      header-align="center"
    >
    </el-table-column>
 <el-table-column
  label="续费人员"
  align="center"
  header-align="center">
  <template slot-scope="{row}">
    {{ row.username === null ? '暂无' : row.username }}
  </template>
</el-table-column>
     <el-table-column
      prop="costtype"
      label="支付类型"
       align="center"
      header-align="center"
     >
       <template slot-scope="{row}">
    {{ row.costtype === null ? '暂无' : row.costtype }}
  </template>
    </el-table-column>
     <el-table-column
      prop="paymoney"
      label="缴费金额"
       align="center"
      header-align="center"
     >
    </el-table-column>
     <el-table-column
      prop="paylevel"
      label="缴费优先级"
       align="center"
      header-align="center"
     >
    </el-table-column>
     <el-table-column
     class="text-e"
      prop="paytime"
      :formatter="formatTime"
      show-overflow-tooltip
      label="支付时间"
       align="center"
      header-align="center"
     >
         <template slot-scope="{row}">
    {{ row.paytime === null ? '暂无' : row.paytime.replace('T', ' ').slice(0, 16) }}
  </template>
    </el-table-column>
    <el-table-column
      prop="paystatus"
      align="center"
      header-align="center"
      label="支付状态">
            <template slot-scope="{row}">
    {{ row.paystatus === 2 ? '未支付' : "已支付" }}
  </template>
    </el-table-column>
     <el-table-column
       width="240"
        align="center"
      header-align="center"
        label="操作">
      <template slot-scope="scope">
        <el-button
        style="color: #89BCEB;"
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">查看</el-button>

         <el-button @click="handleOut(scope.$index, scope.row)">导出</el-button>

        <el-button
          size="mini"
        
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
 <div class="page">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </div>
            </div>
       </div>
    </div>
</template>

<script>
import axios from "axios"
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
export default {
data(){
    return{
     
   total:null,
   size:10,
    Loading: false,
   tableData: [],

currentPage4: 0,
        abc:false,
        qbz:true,
 form: {
          name: '',
          product: '',
         type:null,
          delivery: false,
          status:null,
          sum:null,
          desc: '',
          value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
          priority:''
        }
    }
},
created(){
    this.Loading = true;
        setTimeout(() => {
          this.Loading = false;
        }, 500);
    this.getList()
},
  methods: {

  exportAll() {
 


       this.$confirm('确认导出缴费列表?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
               this.exportExcel(this.tableData, '全部数据');
          this.$message({
            type: 'success',
            message: '导出成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '导出失败'
          });          
        });
    },

    // 处理单行导出
handleOut(index, row) {
  if (!row.payname || !row.paytime) {
    this.$message.warning('该行数据不完整，无法导出');
    return;
  }
  this.exportExcel([row], `导出-${row.payname}`);
},

    // 通用导出方法
  exportExcel(data, fileName = '数据导出') {
  try {
    if (!data || !Array.isArray(data) || data.length === 0) {
      this.$message.warning('没有可导出的数据');
      return;
    }

    // 处理表头和数据
    const headers = [
      { label: '续费产品', prop: 'payname' },
      { 
        label: '续费人员', 
        prop: 'username',
        formatter: (val) => val || '暂无'
      },
      { 
        label: '支付类型', 
        prop: 'costtype',
        formatter: (val) => {
          const types = { 1: '支付宝支付', 2: '微信支付', 3: '银联支付' };
          return types[val] || '未知类型';
        }
      },
      { label: '缴费金额', prop: 'paymoney' },
      { label: '缴费优先级', prop: 'paylevel' },
      { 
        label: '支付时间', 
        prop: 'paytime',
        formatter: (val) => {
          if (!val) return '--';
          const date = new Date(val);
          return isNaN(date) ? '--' : 
            date.toISOString().slice(0, 16).replace('T', ' ');
        }
      },
      { 
        label: '支付状态', 
        prop: 'paystatus',
        formatter: (val) => val === 2 ? '未支付' : '已支付'
      }
    ];

    // 构建数据行（修复括号问题）
    const dataRows = data.map(row => 
      headers.map(h => h.formatter 
        ? h.formatter(row[h.prop]) 
        : row[h.prop]
      )
    );

    // 创建工作簿
    const worksheet = XLSX.utils.aoa_to_sheet([
      headers.map(h => h.label),
      ...dataRows
    ])
    
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

    // 生成文件
    const excelBuffer = XLSX.write(workbook, {
      bookType: 'xlsx',
      type: 'array'
    })

    // 保存文件
    const blob = new Blob([excelBuffer], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    saveAs(blob, `${fileName}_${new Date().getTime()}.xlsx`)

  } catch (error) {
    console.error('[导出错误]', error)
    this.$message.error(`导出失败: ${error.message}`)
  }
},

 handleExportAll() {
  this.exportExcel(this.tableData, '续费列表_当前页');
},




 
 
 

 



        handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.size=val
          this.getList()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.currentPage4=val-1
          this.getList()
      },
     formatTime(row, column, cellValue) {
    // 示例处理：将 "2023-10-01T14:30:00" 转为 "2023-10-01 14:30"
    return cellValue ? 
      cellValue.replace('T', ' ').slice(0, 16) : 
      '--';
  },
     //查看
       handleEdit(index, row) {
        console.log(index, row);
        const token = sessionStorage.getItem('token');
          axios.get('http://community.byesame.com/cost/getCostDetail',{
            params:{
                id:row.id,
                token:token
            }
         }).then((res)=>{
        this.$router.push({
  name: 'payDetail',
  query: {
    detailId: row.id // 传递参数 id=123
  }
});
         })
      },
    //   删除
      handleDelete(index, row) {
        console.log(index, row);



    const token = sessionStorage.getItem('token');
   
    

  
         
         this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           
         axios.get('http://community.byesame.com/cost/delCostData',{
            params:{
                id:row.id,
                token:token
            }
         })
 
         
        this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
            
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      




     
      },
    //   导出
   
      getList() {


         axios.get('http://community.byesame.com/cost/getPayMessage',{
            params:{
                currPage:this.currentPage4,
                pageNum:this.size
            }
         }).then((res)=>{
            console.log(res.data);
            this.tableData=res.data.data
            this.total=res.data.total
            
         })
      },
    lBlock(){
     this.abc=false
     this.qbz=true
    },
    lNone(){
console.log(1);
this.abc=true
this.qbz=false


    },
    //搜索
    submitForm() {
  this.$refs.form.validate((valid) => {
    if (valid) {
      axios.get('http://community.byesame.com/cost/getPayMessage', {
        params: {
          username: this.form.name,
          payname: this.form.product,
          costtype: this.form.type,
          coststatus: this.form.status,
          startDate: this.form.date1?.[0]?.getTime() || '', // 时间戳
          endDate: this.form.date1?.[1]?.getTime() || '',
          paymoney: this.form.sum,
          paylevel: this.form.priority,
          currPage: 0, // 同步当前页码
          pageNum: this.size
        }
      }).then(res => {
        // 更新表格数据
        this.tableData = res.data.data;
        this.total = res.data.total;
      });
    } else {
      console.log('验证失败');
    }
  });
},

  resetForm(form) {
        this.$refs[form].resetFields();
          this.currentPage4=0
         this.Loading = true;
        setTimeout(() => {
          this.Loading = false;
        }, 500);

          this.getList()
         
      }
    },
 
    


}
</script>

<style scoped>
 .left-inner{
  height: 600px;
 
 }
::v-deep .el-table__row {
  height: 50px;  /* 设置行高为50px */
}

::v-deep .el-table td {
  padding: 8px 0;  /* 调整单元格上下间距 */
}
 .text-e{
            /* 文本不换行 */
            white-space: nowrap  !important;
            /* 超出隐藏 */
            overflow: hidden  !important;
            /* 显示省略号 */
            text-overflow: ellipsis  !important;
        }
/* 在你的样式文件中添加 */
.el-table .el-table__row {
  height: 50px; /* 设置行高为 50px */
}
::v-deep .el-table__header th {
  background-color: #EEF1F6 !important;  /* 表头背景色 */
  font-weight: bold !important;         /* 字体加粗 */
  color: black !important;               /* 字体颜色 */
  font-size: 14px !important;
}


::v-deep .el-form-item {
  display: flex;
  flex-direction: column;
}

::v-deep .el-form-item__label {
  float: none;
  width: auto !important;
  text-align: left;
  padding-bottom: 8px;
  line-height: 1;
  transform: none;
}

::v-deep .el-form-item__content {
  margin-left: 0 !important;
}
.content{
    width: 100%;
    display: flex;
    justify-content: space-between;
    background-color: #F0F0F0;
}
.left{
    
    width: 25%;
    height: 700px;
    background-color: white;
    padding: 20px;
    box-sizing: border-box;
    
}
.right{
    width: 74%;
    padding: 20px;
    box-sizing: border-box;
   height: 700px;
    background-color: white;
}
.right-top{
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}
</style>
<style>

body {
  margin: 0;
  background: #F0F0F0 !important; /* 使用 !important 确保覆盖其他样式 */
}
.page{
  text-align: right;
  margin-top: 10px;
}
</style>